package cn.maiyar.gateway.config;

import cn.maiyar.gateway.nacos.NacosRouteDefinitionRepository;
import cn.maiyar.gateway.NacosRoutesProperties;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Properties;

/**
 * 动态路由配置
 *
 * @author c.c
 */
@Slf4j
@ConditionalOnProperty(prefix = "meta.gateway.dynamicRoute", name = "enabled", havingValue = "true")
@EnableConfigurationProperties(NacosRoutesProperties.class)
public class NacosDynamicRoutesConfig {

    @Resource
    private ApplicationEventPublisher publisher;

    @Configuration
    @ConditionalOnProperty(prefix = "meta.gateway.dynamicRoute", name = "dataType", havingValue = "nacos", matchIfMissing = true)
    public class NacosDynamicRoute {

        @Bean
        public NacosRouteDefinitionRepository nacosRouteDefinitionRepository(NacosRoutesProperties gatewayProperties) {
            ConfigService configService = this.initConfigService(gatewayProperties);
            if (configService == null) {
                log.warn("Nacos Route Init ConfigService Fail!");
            }
            return new NacosRouteDefinitionRepository(publisher, gatewayProperties, configService);
        }

        /**
         * 初始化网关路由 nacos config
         *
         * @return
         */
        private ConfigService initConfigService(NacosRoutesProperties gatewayProperties) {
            try {
                Properties properties = new Properties();
                properties.setProperty("serverAddr", gatewayProperties.getAddress());
                properties.setProperty("namespace", gatewayProperties.getNamespace());
                return NacosFactory.createConfigService(properties);
            } catch (Exception e) {
                log.error("Nacos Route Init ConfigService Error :", e);
                return null;
            }
        }
    }
}
